/**
 * Created by gongxun on 16/11/18.
 */

var GameHelper = function(){
    var that = [];

    //正式版1.6.0 测试版1.2.6
    that.version = "1.2.6";

    that.shenheVersion = "1.0.4";

    //本地包版本号 最新版本为1.0.4
    that.baseVersion = "1.0.4";

    // that.htmlHost = "http://192.168.1.222";
    // that.htmlHost = "http://api.qixinxx.com";
    // that.htmlHost = "http://47.94.42.88";
    // that.htmlHost = "http://47.94.43.188";
    that.htmlHost = "http://59.110.40.5";

    //正式版本填true
    that.isRead = false;

    //正式版本填false 是否获取在线可用服务器
    that.isTestVersion = true;

    that.isIosCheck = false;

    that.developerVersion = "2.0";

    //TODO
    // that.webSocketIpTest = "ws://192.168.1.222:10086/";
    that.webSocketIpTest = "ws://59.110.40.5:10086/";
    // that.webSocketIpTest = "ws://59.110.40.5:18888/";    //代理
    // that.webSocketIpTest = "ws://343l97b267e0y23o.gfvip02aj.com:10087/";
    // that.webSocketIpTest = "ws://192.168.1.200:10086/";
    // that.webSocketIpTest = "ws://t7i179p52j396fy0.gfvip02aj.com:10086/";

    // that.webSocketIpReal = "ws://192.168.1.222:10086/";
    that.webSocketIpReal = "ws://t7i179p52j396fy0.gfvip02aj.com:10086/";
    // that.webSocketIpReal = "ws://59.110.40.5:10086/";

    //当前连接的网关
    // that.websocketIpCur = "ws://t7i179p52j396fy0.gfvip02aj.com:10086/";
    that.websocketIpCur = "ws://59.110.40.5:10086/";

    //网关
    that.websocketIps = [];

    that.appHomeUrl = "http://www.qixinxx.com/xiazai/index.html";

    that.androidDownUrl = "http://qxkwx.oss-cn-beijing.aliyuncs.com/download/qixinkwx_1_0_4.apk";

    that.shareBaseUrl = "http://www.qixinxx.com/share?";
    // that.shareBaseUrl = "http://openapp.16youxi.com?";

    //维护状态cdn
    that.maintainUrl = "http://qxkwx.oss-cn-beijing.aliyuncs.com/testGame1/weihu";
    // that.maintainUrl = "http://192.168.1.200/weihu";

    //获取服务列表cdn
    that.mainServerStatus = "http://qxkwx.oss-cn-beijing.aliyuncs.com/7f227";
    // that.mainServerStatus = "http://192.168.1.200/config/7f227";

    //0柒鑫 1乐翻 2新蜂
    that.projectCode = 0;

    that.projectName = "柒鑫";

    that.testVersion = 0;

    //更新审核状态
    that.updateIsIosCheck = function(isIosCheck){
        that.isIosCheck = !!isIosCheck;
        cc.log("当前审核状态:" + (that.isIosCheck ? "审核" : "未审核"));
        mo.eventHelper.dispatch("updateIsIosCheck");
    };

    //设置登录ip
    that.setWebsocketIps = function(ips){
        // that.websocketIps = ips;
        // if (that.websocketIps.length == 0){
        //     mo.showRoomMsgShow("网关获取失败");
        //     return false;
        // }
        //
        // // if (mo.gameWsManager.currentWs != null){
        // //     if (that.findValueForArray(that.websocketIps, mo.gameWsManager.currentWs) != null){
        // //         that.websocketIpCur = mo.gameWsManager.currentWs;
        // //         return true;
        // //     }
        // // }
        //
        // var ipindex = that.findValueForArray(that.websocketIps, that.websocketIpCur);
        // var index = 0;
        // if (ipindex == null){
        //     // index = parseInt(Math.random() * that.websocketIps.length)
        //     index = 0;
        // }else{
        //     if (mo.gameWebsocket.mIsWsError){
        //         index = (ipindex + 1) % that.websocketIps.length;
        //     }else{
        //         index = ipindex;
        //     }
        // }
        // that.websocketIpCur = that.websocketIps[index];

        return true;
    };

    that.setTextString = function(text, content){
        // text.ignoreContentAdaptWithSize(false);
        // text.setTextAreaSize(cc.size(300,60));
        // text.setString("");
        // text.ignoreContentAdaptWithSize(true);
        if (text == undefined){
            cc.log("warring text is undefined... content:" + content);
            return;
        }

        text.setString(content);
        text.setContentSize(text.getAutoRenderSize());
    };

    that.loadTextureImage = function(image, file, texType){
        image.ignoreContentAdaptWithSize(false);
        image.ignoreContentAdaptWithSize(true);
        if (texType != undefined){
            image.loadTexture(file, texType);
        }else{
            image.loadTexture(file);
        }
    };

    that.fixIosText = function(root){
        if (root){
            if (root.getName().substr(0, 5) === "Text_"){
                root.ignoreContentAdaptWithSize(true);
            }
            var arrayRootChildren = root.getChildren();
            var length = arrayRootChildren.length;
            for (var i = 0; i < length; i++) {
                var child = arrayRootChildren[i];
                that.fixIosText(child);
            }
        }
    };

    that.getIsPhoneNum = function(mobile){
        if(mobile.length == 0) {
            return false;
        }
        if(mobile.length != 11) {
            return false;
        }

        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if(!myreg.test(mobile))
        {
            return false;
        }
        return true;
    };

    that.getTimestamp = function(){
        return Math.round(new Date().getTime()/1000);
    };

    that.getMillisecond = function(){
        return new Date().getTime();
    };

    that.getFullString = function(src, char, len){
        var result = "";
        for (var i = 0; i < len; i++){
            result += char;
        }
        result += src;
        return result.substr(result.length - len);
    };

    that.getTimeYYMMDD = function(clientData){
        var date;
        if (clientData == undefined){
            date = new Date();
        }else{
            date = clientData;
        }
        var seperator1 = "-";
        var seperator2 = ":";
        var year = date.getFullYear();
        var month = that.getFullString((date.getMonth() + 1), "0", 2);
        var day = that.getFullString(date.getDate(), "0", 2);
        var hours = that.getFullString(date.getHours(), "0", 2);
        var min = that.getFullString(date.getMinutes(), "0", 2);
        var sec = that.getFullString(date.getSeconds(), "0", 2);
        return year + seperator1 + month + seperator1 + day + " " + hours + seperator2 + min + seperator2 + sec;
    };

    //返回两个数组是否有交集
    that.getIntersectionForArray = function(array1, array2){
        var temp = {};
        for (var i = 0; i < array1.length; i++){
            var key = array1[i];
            temp[key] = 1;
        }

        for (var i = 0; i < array2.length; i++){
            var key = array2[i];
            if (temp[key] != undefined){
                return true;
            }
        }
        return false;
    };

    //返回两个数组是否有交集 优化
    that.getIntersectionForMap = function(array1, map2){
        for (var i = 0; i < array1.length; i++){
            var key = array1[i];
            if (map2[key] != undefined){
                return true;
            }
        }
        return false;
    };

    //b是否包含s  s和b都是不重复的
    that.getContainArrayAndReturnLeft = function(bigArray, smallArray){
        var result = [];
        var isContain = true;
        for(var i = 0; i < bigArray.length; i++){
            var num = bigArray[i];

            var find = false;
            for (var j = 0; j < smallArray.length; j++){
                if (smallArray[i] == num){

                }else{

                }
            }
        }

        var temp = [];
        for (var i = 0; i < bigArray.length; i++){
            temp.push(bigArray[i]);
        }

        var isContain = true;
        for (var i = 0; i < smallArray.length; i++){
            var num = smallArray[i];
            var isFind = false;
            for (var j = 0; j < temp.length; j++){
                var tempNum = temp[j];
                if (tempNum == num){
                    isFind = true;
                    temp.splice(j, 1);
                    break;
                }
            }
            if (!isFind){
                isContain = false;
                break;
            }
        }

        if (isContain){
            return [true, temp];
        }else{
            return [false, []];
        }
    };

    //返回不重复的数组
    that.getUniqueArray = function(nums){
        var h = {};
        var arr = [];

        for(var i = 0; i < nums.length; i++){
            //对元素进行判断，看是否已经存在表中，如果存在则跳过，否则存入临时数组
            if(!h[nums[i]]){
                //存入hash表
                h[nums[i]] = true;
                //把当前数组元素存入到临时数组中
                arr.push(nums[i]);
            }
        }
        return arr;
    };

    //过滤数组
    that.getFilterArrayForArray = function(array, filterArray){
        var checkArray = function(v){
            return that.findValueForArray(filterArray, v) == null;
        };

        var result = array.filter(checkArray);
        return result;
    };

    //返回是否存在 存在返回索引 不存在返回null
    that.findValueForArray = function(array, value){
        var result = null;
        for (var i = 0; i < array.length; i++){
            if (value === array[i]){
                result = i;
                break;
            }
        }
        return result;
    };

    //返回是否存在 排除indexs里的
    that.findNumApartIndexs = function(array, num, indexs){
        var rIndex = null;
        for (var i = 0; i < array.length; i++){
            var isContinue = false;
            for (var j = 0; j < indexs.length; j++){
                if (i == indexs[j]){
                    isContinue = true;
                    break;
                }
            }
            if (isContinue){
                continue;
            }

            if (array[i] == num){
                rIndex = i;
                break;
            }
        }
        return rIndex;
    };

    //返回数组是否相等 长度和内容一致
    that.cmpareArray = function(array1, array2){
        if (array1.length != array2.length){
            return false;
        }

        for (var i = 0; i < array1.length; i++){
            if (array1[i] != array2[i]){
                return false;
            }
        }

        return true;
    };


    that.logDebug = function(content){
        cc.log(content);
    };

    that.getIsTouchEnd = function(type){
        if (type == ccui.Widget.TOUCH_ENDED){
            mo.soundHelper.playButtonClick();
            return true;
        }
        return false;
    };

    that.getIsTouchEndMenuOpen = function(type){
        if (type == ccui.Widget.TOUCH_ENDED){
            mo.soundHelper.playMenuOpenClick();
            return true;
        }
        return false;
    };

    that.getIsTouchEndMenuClose = function(type){
        if (type == ccui.Widget.TOUCH_ENDED){
            mo.soundHelper.playMenuCloseClick();
            return true;
        }
        return false;
    };


    //微信个人分享
    that.onWxInvite = function(gameName, tableId, pwd, title, description){
        if (!cc.sys.isNative || that.isIosCheck){
            mo.showRoomMsgShow("分享成功");
            return;
        }
        mo.nativeHelper.onWxInvite(gameName, tableId, pwd, title, description);
    };

    //微信分享到网页
    that.onWxShareWeb = function(title, description, url){
        if (!cc.sys.isNative || that.isIosCheck){
            mo.showRoomMsgShow("分享成功");
            return;
        }

        mo.nativeHelper.onWxShareWeb(title, description, url);
    };

    //微信分享到文字
    that.onWxShareText = function(title){
        if (!cc.sys.isNative || that.isIosCheck){
            mo.showRoomMsgShow("分享成功");
            return;
        }

        mo.nativeHelper.onWxShareText(title);
    };

    //微信朋友圈分享
    that.onWxShare = function(content){
        if (!cc.sys.isNative|| that.isIosCheck){
            mo.showRoomMsgShow("分享成功");
            return;
        }
        var fileName = "shareImage.png";
        mo.nativeHelper.onWxShare(content, fileName);
    };

    //微信分享图片到朋友
    that.onWxShareFriend = function(title, description){
        if (!cc.sys.isNative || that.isIosCheck){
            mo.showRoomMsgShow("分享成功");
            return;
        }

        var time1 = "image";
        var time2 = that.getMillisecond() + "";

        // var fileName = "Share" + time1 + ".png";
        // var scalingFileName = "Scaling" + time2 + ".png";
        var fileName = "Share" + time1 + ".jpg";
        var scalingFileName = "Scaling" + time2 + ".jpg";
        mo.nativeHelper.onWxShareFriend(title, description, fileName, scalingFileName);
    };

    //加载图片
    that.loadImageForUrl = function(imageView, url){
        if (cc.sys.isNative){
            mo.nativeHelper.setImageUrr(imageView, url);
        }
    };

    //返回itemid对应的中文
    that.getItemIdForCHS = function(itemid){
        if (itemid == 20001){
            return "房卡";
        }else if (itemid == 20002){
            return "荣誉值";
        }else if (itemid == 20000){
            return "游戏点";
        }
        return "未知货币";
    };

    //返回当前是否是旋转状态
    that.getIsRotation = function(){
        if (mo.gameMainLayer != null){
            return mo.gameMainLayer.getCurrentIsRotation();
        }else{
            return false;
        }
    };

    //设置root的Text_text文字
    that.setRootTitleText = function(root, text){
        var textui = mo.seekWidgetByName(root, "Text_text");
        if (textui != null){
            that.setTextString(textui, text);
        }
    };

    //过滤玩家昵称
    that.getUserNickFilterForCount = function(nick, count){
        var result = nick;
        if (nick.length > count){
            result = result.substr(0, count) + "..";
        }
        return result;
    };

    //过滤玩家昵称
    that.getUserNickFilter = function(nick){
        var count = 5;
        return that.getUserNickFilterForCount(nick, count);
    };

    //返回手机类型
    that.getDeviceType = function(){
        cc.log("sys os:" + cc.sys.os);
        if (cc.sys.os == "iOS"){
            return 0;
        }else if (cc.sys.os == "Android"){
            return 1;
        }else {
            return 2;
        }
    };

    //强制升级底包 isAuto true:强制升级 false:不强制升级
    that.checkBaseVersion = function(musUpdate){
        if (!cc.sys.isNative){
            return false;
        }

        if (typeof (mo.nativeConfig.getBaseVersion) == typeof undefined){
            //本地不能自动升级
            mo.showMsgDialogText("为保证您的游戏体验，请升级最新客户端后再进行游戏 下载地址" + that.appHomeUrl);
            if (musUpdate != undefined && musUpdate){
                return true;
            }else{
                return false;
            }
        }

        var isUpdate = false;
        var basevarsion = mo.nativeConfig.getBaseVersion();
        if (basevarsion != that.baseVersion){
            isUpdate = true;
        }

        if (isUpdate){
            //需要强制升级
            // var showMsg = "为保证您的游戏体验，请升级最新客户端后再进行游戏";
            var showMsg = "发现新游戏底包\n新游戏底包将提高游戏稳定性，并降低游戏中的流量消耗\n推荐所有用户进行更新";
            mo.showMsgDialogOk(
                showMsg,
                function(){

                    var sureUpdate = "是否确定下载新游戏底包？\n确定后将会切换到浏览器，请在浏览器中点击'安卓下载'，下载安装之后就可以马上开始游戏啦)";
                    if (cc.sys.os === cc.sys.OS_IOS){
                        sureUpdate = "是否确定下载新游戏底包？\n确定后将会切换到浏览器，请在浏览器中点击'苹果下载'，完成底包更新)";
                    }
                    mo.showMsgDialogOkAndCancel(sureUpdate, function(){
                        mo.nativeHelper.jumpWebUrl(that.appHomeUrl);
                    }, this, function(){

                    }, this);

                    //android程序内下载
                    // mo.nativeHelper.updatePackage(that.androidDownUrl, function(success){
                    //     if (success){
                    //
                    //     }else {
                    //         mo.nativeHelper.jumpWebUrl(that.appHomeUrl);
                    //     }
                    // });
                },
                this
            );
        }

        return isUpdate;
    };

    //提示维护信息
    that.checkWeiHuInfo = function(){
        if (!cc.sys.isNative){
            return;
        }

        //维护开始时间 2017-7-7 4:00
        // var startTime = 1499364000000;
        var startTime = 1499371200000;

        //维护结束时间 2017-7-7 8:00
        var endTime = 1499385600000;
        // var endTime = 1499365440000;

        //当前时间
        var nowTime = new Date();

        if (startTime > nowTime){
            return;
        }

        var jiange = endTime - nowTime;

        var fenzhong = jiange / 1000 / 60;
        cc.log("维护时间 间隔是:" + jiange + " 分钟数:" + fenzhong);

        if (jiange > 0){
            mo.showMsgDialogOk(
                "游戏例行维护，预计维护时间为4个小时 具体维护时间：7月7日04:00:00-7月7日08:00:00",
                function(){
                    that.checkWeiHuInfo();
                },
                this
            );
        }
    };

    //返回url参数
    that.getUrlParam = function(url){
        var param = {};

        var num = url.indexOf("?");
        var temp = url.substr(num + 1);
        var arr = temp.split("&");
        for(var i = 0; i < arr.length; i++){
            num = arr[i].indexOf("=");
            if(num > 0){
                name = arr[i].substring(0, num);
                value = arr[i].substr(num + 1);
                param[name] = value;
            }
        }
        return param
    };

    //返回房间号对应的游戏文字
    that.getGameNameForRoomId = function (gameId) {
        if (gameId < 200000){
            return "kwx";
        }else if (gameId < 300000){
            return "nn";
        }else if (gameId > 300000 && gameId < 400000){
            return "whmj";
        }else if (gameId > 400000 && gameId < 500000){
            return "gsbdx";
        }else if (gameId > 500000 && gameId < 600000){
            return "psz";
        }else if (gameId > 600000 && gameId < 700000){
            return "kwx";
        }else if (gameId > 700000 && gameId < 800000){
            return "dzpk";
        }else if (gameId > 800000 && gameId < 900000){
            return "dtj";
        }else if (gameId > 900000 && gameId < 1000000){
            return "pdk";
        }
    };

    //返回游戏文字对应的中文名字
    that.getCHSNameForGameName = function(gameName){
        if (gameName == "kwx"){
            return "卡五星";
        }else if (gameName == "nn"){
            return "牛牛";
        }else if (gameName == "gsbdx"){
            return "推筒子";
        }else if (gameName == "psz"){
            return "拼三张";
        }else if (gameName == "whmj"){
            return "武汉麻将";
        }else if (gameName == "dzpk"){
            return "德州扑克";
        }else if (gameName == "dtj"){
            return "拼天九";
        }else if (gameName == "ddz"){
            return "斗地主";
        }else if (gameName == "pdk"){
            return "跑得快";
        }
    };

    //返回规则说明文字
    that.getRuleConfigSummary = function(config, gameName, roomId){
        var result = "";
        if (gameName == "kwx"){
            //襄阳玩法,8局,加飘,买独马
            var wanfa = ["孝感玩法", "襄阳玩法", "十堰玩法", "随州玩法"];
            var jiapiao = ["不加飘", "加飘"];
            var shukan = ["不加坎", "软坎", "硬坎"];
            var allTop = ["", "封顶8番", "封顶16番"];
            var maima = ["不买马", "买独马", "买散马"];
            var maimaRule = ["亮倒自摸买马", "自摸买马"];
            var ting12 = "少于12张不能明";
            var pingdao = ["半频道", "全频道"];
            var shanglou = ["不上楼", "上楼"];
            var chajiao = ["不查叫", "查叫"];

            result += wanfa[config.ruleid - 1] + " ";
            result += config.maxpan + "盘 ";
            if (roomId != undefined){
                if (roomId > 100000 && roomId < 200000){
                    result += "3人场 ";
                }else{
                    result += "2人场 ";
                }
            }
            result += jiapiao[config.piao] + " ";
            if (config.ruleid == 1){
                result += maima[config.horse] + " ";
                if (config.horse != 0){
                    result += maimaRule[config.zm] + " ";
                }
                result += shukan[config.kan] + " ";
                result += allTop[parseInt(config.alltop / 8)];
                result += (config.ting12 == 1 ? (" " + ting12) : "")
            }else if (config.ruleid == 2){
                result += maima[config.horse] + " ";
                if (config.horse != 0){
                    result += maimaRule[config.zm] + " ";
                }
                result += pingdao[config.pd]
            }else if (config.ruleid == 3){
                result += maima[config.horse] + " ";
                if (config.horse != 0){
                    result += maimaRule[config.zm] + " ";
                }
                result += shanglou[config.sl] + " ";
                result += chajiao[config.cj] + " ";
                result += pingdao[config.pd];
            }else if (config.ruleid == 4){
                result += maima[config.horse];
                if (config.horse != 0){
                    result += " " + maimaRule[config.zm];
                }
            }
        }else if (gameName == "nn"){
            //随州玩法,10局,轮庄,全扣,加倍
            var wanfa = ["大众玩法", "随州玩法"];
            var zhuang = ["轮庄", "连庄", "霸王庄"];
            // var koupai = ["全扣", "扣两张", "扣一张"];
            result += wanfa[config.ruleid - 1] + " ";
            result += config.maxpan + "盘 ";
            result += zhuang[config.hosttype] + " ";
            if (config.addratetime == 0){
                result += "每次选分";
            }else{
                result += "固定" + config.basepoint + "分";
            }
        }else if (gameName == "gsbdx"){
            //大众玩法,10局,轮庄,加倍
            var wanfa = ["大众玩法", "", "河南玩法"];
            var zhuang = ["轮庄", "连庄", "霸王庄"];
            result += wanfa[config.ruleid - 1] + " ";
            result += config.maxpan + "盘 ";
            result += zhuang[config.hosttype] + " ";
            if (config.addratetime == 0){
                result += "每次选分";
            }else{
                result += "固定" + config.basepoint + "分";
            }
        }else if (gameName == "psz"){
            //6盘,封顶轮数：5,比牌轮数:1,闷3轮
            result += config.maxpan + "盘 ";
            result += "封顶轮数:" + config.open + " ";
            result += "比牌轮数:" + config.bi + " ";
            result += "闷" + config.men + "轮 ";
            result += "豹子奖" + config.aaap + "分";
            if (config.ssc == 1){
                result += " " + "没看牌玩家不能跟看牌玩家比牌";
            }
        }else if (gameName == "whmj"){
            var kaikou = ["开口翻", "口口翻"];
            var wanfa = ["红中发财杠", "赖子皮杠"];
            result += config.maxpan + "盘 ";
            result += wanfa[config.ruleid - 1] + " ";
            result += kaikou[config.openrate - 1];
        }else if (gameName == "dzpk"){
            result += config.maxpan + "盘 ";
            result += "大盲注:" + config.basepoint + " ";
            result += (config.men == 0 ? "不闷" : "闷一轮");
        }else if (gameName == "dtj"){

            if(config.guo == 1){
                result += " 有锅 ";
                // result += (this.mGameConfig.xuguo == 0 ? "不" : "可") + "续锅 ";
                result += "锅底" + config.guomax + "分 ";
            }else{
                result += "无锅 ";
                var zhuang = ["轮庄", "抢庄", "霸王庄"];
                result += zhuang[config.hosttype] + " ";
                if (config.addratetime == 0){
                    result += "每次选分 ";
                }else{
                    result += "固定" + config.basepoint + "分 ";
                }
            }

            var paijiu = ["大牌九", "小牌九"];
            result += paijiu[config.paijiu] + " ";

            if(config.paijiu == 0){
                result += config.maxpan + "盘 ";
            }

            result += (config.ruleid == 1 || config.ruleid == 3) ? "有鬼子 " : "无鬼子 ";
            result += (config.ruleid == 1 || config.ruleid == 4) ? "有天九王 " : "无天九王 ";
        }else if (gameName == "ddz"){
            result += config.maxpan + "盘 ";
        }else if (gameName == "pdk"){
            result += config.maxpan + "盘 ";
            var hosttype = ["红桃三先出", "赢家先出"];
            var alltop = ["不封顶", "8张封顶"];
            var ruletriple = ["三带一", "三带二"];
            var ruleairplane = ["单翼", "双翼"];
            var rulefour = ["四带三 ", "不能四带三"];
            result += hosttype[config.hosttype] + " ";
            result += alltop[config.alltop] + " ";
            result += ruletriple[config.ruletriple] + " ";
            result += ruleairplane[config.ruleairplane] + " ";
            result += rulefour[config.rulefour] + " ";
        }

        //生死战特殊
        if (config.lod != undefined && config.lod != 0){
            result += ",生死战:" + config.lod;
        }

        return result;
    };

    //邀请入桌
    that.inviteGame = function(config, gameName, roomId){
        var configSummary = mo.gameHelper.getRuleConfigSummary(config, gameName, roomId);
        configSummary += "，就等你来了(点击加入)";

        var title = "桌号:[" + roomId + "]" + "-" + mo.gameHelper.projectName + "-" + that.getCHSNameForGameName(gameName);
        var description = configSummary;
        that.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(1, roomId));
    };

    //分享录像
    that.shareReplay = function(config, gameName, roomId, replayId){
        var configSummary = mo.gameHelper.getRuleConfigSummary(config, gameName, roomId);
        configSummary += "，在游戏中输入录像id就能看到我的精彩回放了";

        var title = "录像id:" + replayId.substr(7) + "-" + mo.gameHelper.projectName + "-" + that.getCHSNameForGameName(gameName);
        var description = configSummary;

        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(2, replayId.substr(7)));
    };

    //检测对象是否是json格式
    that.getIsJson = function(obj){
        if (typeof obj == 'string') {
            try {
                JSON.parse(obj);
                return true;
            } catch(e) {
                return false;
            }
        }
        return false;
    };

    //替换json key关键字
    that.replaceJsonTokwx = function(json, outjson){
        //直接值
        if (Array.isArray(json)){
            for(var i = 0; i < json.length; i++){
                var item = json[i];
                json[i] = that.replaceJsonTokwx(item, {});
            }
            return json;
        }else if (typeof(json) != "object"){
            return json;
        }

        //object
        for(var key in json){
            var value = json[key];
            var type = typeof(value);
            // cc.log("type:" + type + " key:" + key + " value:" + value);

            if (Array.isArray(value)){
                // cc.log("is array");
                for(var i = 0; i < value.length; i++){
                    var item = value[i];
                    value[i] = that.replaceJsonTokwx(item, {});
                }
            } else if (type == "object" && value != null){
                value = that.replaceJsonTokwx(value, {});
            }

            var newKey = key.replace(/kwxpp/g, "kwx");
            outjson[newKey] = value;
        }
        return outjson;
    };

    //替换json key关键字
    that.replaceJsonTokwxpp = function(json, outjson){
        //直接值
        if (Array.isArray(json)){
            for(var i = 0; i < json.length; i++){
                var item = json[i];
                json[i] = that.replaceJsonTokwx(item, {});
            }
            return json;
        }else if (typeof(json) != "object"){
            return json;
        }

        //object
        for(var key in json){
            var value = json[key];
            var type = typeof(value);
            // cc.log("type:" + type + " key:" + key + " value:" + value);

            if (Array.isArray(value)){
                // cc.log("is array");
                for(var i = 0; i < value.length; i++){
                    var item = value[i];
                    value[i] = that.replaceJsonTokwx(item, {});
                }
            } else if (type == "object" && value != null){
                value = that.replaceJsonTokwx(value, {});
            }

            var newKey = key.replace(/kwx/g, "kwxpp");
            outjson[newKey] = value;
        }
        return outjson;
    };

    //获取session
    that.getCookie = function(name)
    {
        if (!cc.sys.isNative){
            var arr,reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if(arr=document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        }else{
            return null;
        }
    };

    //返回相对node的point
    that.getPointForNode = function(node, point){
        var result = cc.p(0, 0);
        var nodePoint = node.getPosition();
        nodePoint.x = point.x - nodePoint.x;
        nodePoint.y = point.y - nodePoint.y;

        var rotation = node.getRotation();
        var radian = Math.PI / 180 * rotation;

        result = cc.pRotateByAngle(nodePoint, cc.p(0, 0), radian);

        return result;
    };

    //返回节点相对于屏幕的坐标
    that.getNodePointForScene = function(node, point){
        var result = node.getPosition();
        if (point != undefined){
            result = cc.p(point.x, point.y);
        }

        var parent = node;

        while (parent) {
            parent = parent.getParent();
            if (parent) {
                var rect = parent.getBoundingBox();
                var parentPoint = cc.p(cc.rectGetMinX(rect), cc.rectGetMinY(rect));
                result = cc.p(parentPoint.x + result.x, parentPoint.y + result.y);
                break;
            }
        }
        return result;
    };

    //设定剪切相关
    that.setClippingLayout = function(layout){
        if (mo.sceneMainLayer.getPosition().y != 0){
            layout._getClippingRect = function(){
                if (layout._clippingRectDirty) {
                    var rect = layout.getBoundingBox();
                    var point = that.getNodePointForScene(layout, cc.p(rect.x, rect.y));
                    var worldPos = cc.p(point.y, point.x);
                    var scissorWidth = rect.height;
                    var scissorHeight = rect.width;

                    var parent = layout;
                    while (parent) {
                        parent = parent.getParent();
                        if (parent && parent instanceof ccui.Layout && parent.isClippingEnabled()) {
                            layout._clippingParent = parent;
                            break;
                        }
                    }

                    layout._clippingRect.x = worldPos.x;
                    layout._clippingRect.y = worldPos.y;
                    layout._clippingRect.width = scissorWidth;
                    layout._clippingRect.height = scissorHeight;
                    layout._clippingRectDirty = false;
                }
                return layout._clippingRect;
            };
        }
    };

    //测试数据
    that.testInfo = function(){
        var source = [
            "116395,110373,96976","1,10,-11",110373,3,1,
            "105005,112651,117053","-2,-5,7","","",1,
            "97985,118020,97541","-21,49,-28",118020,3,2,
            "95092,95817,114340","14,-24,10","","",2,
            "113641,114422,110373","11,8,-19","","",2,
            "119190,114340,117647","25,14,-39","","",1,
            "90671,112651,103201","-26,7,19","","",2,
            "108164,110373","10,-10","","",2,
            "90671,112651,103201","17,9,-26","","",2,
            "119190,117664,114340","-32,-54,86",114340,3,1,
            "95817,96782,118020","-6,-33,39",118020,3,1,
            "90671,112651,103201","-40,36,4",112651,3,1,
            "117664,114340,119190","22,9,-31","","",1,
            "106103,110373,97475","22,44,-66",110373,3,2,
            "91249,115741,118020","-44,-19,63",118020,3,1,
            "90950,118020,104413","-27,35,-8",118020,3,2,
            "108706,110610,112651","2,-14,12",112651,3,1,
            "112029,114340,104400","-17,7,10","","",1,
            "106103,110373,102277","19,4,-23","","",2,
            "90950,111275,118020","-4,6,-2","","",2,
            "112029,117664,114340","-17,53,-36","","",1,
            "92157,95190,110373","-41,-4,45",110373,3,2,
            "95113,118020,95224","19,-46,27","","",2,
            "116649,113050,112651","14,14,-28","","",1,
            "95113,95224,110373","2,-47,45",110373,3,1,
            "96026,101450,118020","-15,-17,32",118020,3,2,
            "116649,112651,92532","3,-16,13","","",1,
            "115240,114340,107910","1,-37,36","","",1,
            "92157,110373,101450","3,-13,10","","",2,
            "116679,118020,104071","23,-23,0","","",2,
            "107588,114340,117069","-29,52,-23",114340,3,1,
            "91218,112651,96976","-27,66,-39",112651,3,1,
            "95175,118020,95033","-8,7,1","","",2,
            "114422,110373","-1,1","","",2,
            "112651,111170,107569","0,0,0","","",1,
            "106103,95199,114340","-62,2,60",114340,3,2,
            "100169,95175,118020","-37,103,-66","","",2,
            "95153,95199,114340","1,21,-22","","",2,
            "116649,112651,102716","-12,-42,54","","",1,
            "110255,110373,107381","-15,28,-13",110373,3,1,
            "116679,118020,108074","-1,-2,3","","",2,
            "95175,110373,95033","-17,80,-63","","",1,
            "118302,118020,107674","37,-20,-17","","",1,
            "102716,112651,113050","29,-31,2","","",1
        ];


        var scoreList =[

        ];

        var uidList = [

        ];

        for (var i = 0; i < 44; i++){
            var scoreIndex = i * 5 + 1;
            var temp = source[scoreIndex];
            var temp1 = JSON.parse("[" + temp + "]");
            scoreList.push(temp1);

            var uidIndex = i * 5;
            temp = source[uidIndex];
            temp1 = JSON.parse("[" + temp + "]");
            uidList.push(temp1);
        }

        var myUids = [
            114340,
            112651,
            110373,
            118020
        ];

        var loseWins = [];

        for (var i = 0; i < uidList.length; i++){
            var uids = uidList[i];
            var scores = scoreList[i];

            var loseScore = 0;
            for (var j = 0; j < 3; j++){
                uid = uids[j];
                score = parseInt(scores[j]);

                if (uid == undefined){
                    continue;
                }

                if (mo.gameHelper.findValueForArray(myUids, uid)){
                    loseScore = score;
                }
            }

            if (loseScore < 0){
                loseScore = -loseScore;
                for (var j = 0; j < 3; j++){
                    uid = uids[j];
                    score = parseInt(scores[j]);

                    if (uid == undefined){
                        continue;
                    }

                    if (!mo.gameHelper.findValueForArray(myUids, uid)){
                        var findIndex = -1;
                        for (var m = 0; m < loseWins.length; m++){
                            if (loseWins[m].uid == uid){
                                findIndex = m;
                            }
                        }

                        if (findIndex == -1){
                            var loseWin = {};
                            loseWin.uid = uid;
                            loseWin.score = 0;
                            loseWin.count = 0;
                            loseWins.push(loseWin);
                            findIndex = loseWins.length - 1;
                        }

                        if (score >= loseScore){
                            loseWins[findIndex].score += loseScore;
                            loseScore = 0;
                        }else{
                            loseWins[findIndex].score += score;
                            loseScore -= score;
                        }
                        loseWins[findIndex].count += 1;
                    }
                }
            }
        }

        loseWins.sort(function(a, b){
            return b.score - a.score;
        });

        for(var i = 0; i < loseWins.length; i++){
            var loseWin = loseWins[i];
            cc.log("用户id:" + loseWin.uid + " 赢了:" + loseWin.score);
        }

        return;
    };

    //写本地manifest更新文件
    that.updateManifestFile = function(url, version){
        //如果写了文件 就不管了
        // if (version == mo.gameHelper.)

        var writeblePath = jsb.fileUtils.getWritablePath();
        var writeFullPath = writeblePath + "res/projectGame.manifest";
        var writeStr = "";

        if (!jsb.fileUtils.isDirectoryExist(writeblePath + "res")){
            jsb.fileUtils.createDirectory(writeblePath + "res");
        }

        //要生成的文件有3个
        //res/projectGame.manifest
        var dataJson = {};
        dataJson.packageUrl = url;
        dataJson.remoteManifestUrl = url + "/project.manifest";
        dataJson.remoteVersionUrl = url + "/version.manifest";
        dataJson.version = version;
        dataJson.groupVersions = {1 : version};
        dataJson.engineVersion = "3.13.1";
        dataJson.searchPaths = [];
        writeStr = JSON.stringify(dataJson);

        jsb.fileUtils.writeStringToFile(writeStr, writeblePath + "res/projectGame.manifest");
        jsb.fileUtils.writeStringToFile(writeStr, writeblePath + "projectGame.manifest");
        jsb.fileUtils.writeStringToFile(writeStr, writeblePath + "version.manifest");
    };

    //读取本地manifest文件
    that.getManifestFile = function(){
        var writeblePath = jsb.fileUtils.getWritablePath();
        var writeFullPath = writeblePath + "res/projectGame.manifest";
        var result = jsb.fileUtils.getStringFromFile(writeFullPath);
        return result;
    };

    //比较版本号 返回true 就是需要升级了
    that.compareVersion = function(loacl, server){
        if (loacl == null || server == null){
            return false;
        }

        var v1 = loacl.split(".");
        var v2 = server.split(".");

        if (v1.length == v2.length){
            for (var i = 0; i < v1.length; i++){
                var item1 = parseInt(v1[i]);
                var item2 = parseInt(v2[i]);

                if (item1 > item2){
                    return false
                }else if (item2 > item1){
                    return true;
                }
            }
        }

        return false;
    };

    //重新加载整个项目
    that.resetAllProject = function(){
        for (var i = 0; i < Files.length; i++){
            cc.sys.cleanScript(Files[i]);
        }

        cc.loader.loadJs(["src/gameVersion.js"], function(err){
            mo.gameVersion.init();
        });
    };

    //异或算法
    that.yihuoSuanfa = function(str, key){
        var result = "";

        var arrData = new Uint8Array(str.length);
        for (var i = 0; i < str.length; i++){
            arrData[i] = str.charCodeAt(i);
        }

        var keyData = new Uint8Array(key.length);
        for (var i = 0; i < key.length; i++){
            keyData[i] = key.charCodeAt(i);
        }

        var lenght = keyData.length;
        for(var i = 0; i < str.length; i++){
            var temp = arrData[i] ^ keyData[i % lenght];
            result += String.fromCharCode(temp);
        }
        return result;
    };

    return that;
};

mo.gameHelper = new GameHelper();

//common
mo.seekWidgetByName = function(root, name){
    if (!root)
        return null;

    if (root.getName() === name)
        return root;

    var arrayRootChildren = root.getChildren();
    var length = arrayRootChildren.length;
    for (var i = 0; i < length; i++) {
        var child = arrayRootChildren[i];
        var res = mo.seekWidgetByName(child, name);
        if (res !== null)
            return res;
    }
    return null;
};